package com.ykq.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ykq.constant.GatewayConstant;
import org.apache.commons.lang.text.StrTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;

@Configuration
public class JWTCheckFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.如果登录 或者一些放行的接口 就不需要拦截
        //2.拿到URL地址
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();
        if (GatewayConstant.ALLOW_URL.contains(path)) {
            //放行
            return chain.filter(exchange);
        }
        // 不是放行的url 拿到token  放在header里面
        List<String> tokenHeaders = request.getHeaders().get(GatewayConstant.AUTHORIZATION);
        if (!CollectionUtils.isEmpty(tokenHeaders)) {
            String token = tokenHeaders.get(0);
            if (StringUtils.hasText(token)) {
                String jwt = token.replaceAll("bearer", "");
                if (StringUtils.hasText(jwt) && redisTemplate.hasKey(GatewayConstant.TOKEN_JWT_PREFIX + jwt)) {
                    // jwt 不等空 redis也有 放行  把服务端变成有状态的 解决jwt登出问题
                    return chain.filter(exchange);
                }
            }
        }
        //既不是放行 也没有token 直接拦截 返回401 前台就会自动跳转到登录的页面
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("content-type", "application/json;charset=utf-8");
        //2.设置业务响应码
        HashMap<String, Object> map = new HashMap<>(4);
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("msg", "未授权");
        //3.转换写出去
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //使用buffer工厂将字节写好
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer wrap = dataBufferFactory.wrap(bytes);

        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
